/**
*      author: Y_Yao
*      created: 2024-10-26 20:00:50
**/

#include<bits/stdc++.h>

using namespace std;
#define int LL
using LL = long long;
const LL LLINF = 1e18;
const int INF = 0x3f3f3f3f;
const int N = 1e6 + 7;
int p[N],a[N],s[N];
int n;

int Find(int i)
{
    if(a[i] == i) return i;
    else a[i] = Find(a[i]);

    return a[i];
}

void Union(int x1,int x2)
{
    int root1 = Find(x1);
    int root2 = Find(x2);
    if(root1 == root2) return;

    a[root1] = root2;
    s[root2] += s[root1];

}

void solve()
{
    cin >> n;
    for(int i = 1;i <= n;i++)
    {
        cin >> p[i];
        a[i] = i;
        s[i] = 1;
    }

    for(int i = 1;i <= n;i++)
    {
        if(p[i] == i) continue;
        Union(p[i],i);
    }

    int ret = 0;
    for(int i = 1;i <= n;i++)
    {
        if(a[i] == i)
        {
            ret += (s[i] - 1) / 2;
        }
    }

    cout << ret << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int t = 1;
    cin >> t;
    while(t--)
    {
        solve();
    }
    return 0;
}